using Domain.Entities;
using Domain.Entities.Enums;
using Domain.Mail;
using Domain.Misc;
using Domain.Services;
using System;

namespace UserInterface
{
    public partial class ActivateAccount : BoardPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int userId = Convert.ToInt32(Request.QueryString["userId"]);
            string activationKey = Request.QueryString["activationKey"];

            User user = UserService.GetByIdAndActivationKey(userId, activationKey);

            if (user != null)
            {
                if (user.Status == UserStatus.AwaitingActivationByEmail)
                {
                    if (BoardSettingsManager.Instance.Settings.AccountActivationByAdmin)
                    {
                        UserService.UpdateStatus(user, UserStatus.AwaitingActivationByAdmin);
                        MessageTextLiteral.Text = "E-mail activation successful, an administrator still needs to activate your account before you can start using it.";
                    }
                    else
                    {
                        UserService.UpdateStatus(user, UserStatus.Activated);
                        MessageTextLiteral.Text = "E-mail activation successful, you can now log in and start using your account.";
                    }
                }
                else if (user.Status == UserStatus.Reserved)
                {
                    UserService.UpdateStatus(user, UserStatus.Activated);
                    MessageTextLiteral.Text = "Activation successful, you can now log in and start using your account.";
                }
                else if (user.Status == UserStatus.RetrievingPassword)
                {
                    string password = RandomStringGenerator.Generate(8);

                    MailParser mailParser = new MailParser(Server.MapPath("~/Emails/NewPassword.xml"));
                    mailParser.AddBodyTag("Username", user.Username);
                    mailParser.AddBodyTag("Password", password);
                    
                    MailSender mailSender = new MailSender(mailParser);
                    mailSender.AddRecipient(user.Email);
                    mailSender.Send();

                    UserService.UpdatePassword(user, password);
                    UserService.UpdateStatus(user, UserStatus.Activated);
                    MessageTextLiteral.Text = "Your new password has been sent to your e-mail address.";
                }
                else
                {
                    MessageTextLiteral.Text = "Something went wrong.";
                }
            }
            else
            {
                MessageTextLiteral.Text = "Something went wrong.";
            }
        }
    }
}